JAVA基础之"内部类"

一、“内部类”

在这里插入图片描述

在一个.java源文件中,只能定义一个类名与文件名完全一致的公开类。但在面向对象语言中,任意一个类都可以在内部定义另一个类,前者为外部类,后者为内部类。 内部类本身是类的一个属性,与其他属性定义方法一致。

//比如属性字段  访问控制符+是否是静态+类型+变量名称组成
private static String str;
//内部类    访问控制符+是否是静态+类型+名称
private static class Inner{}
private static enum Inner{}
private static interface Inner{}

二、分类

名称说明
静态内部类static class StaticInner{};
成员内部类private class InstancecInner{};
局部内部类定义在方法或表达式内
匿名内部类(new Thread(){}).start();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 下列说法中关于内部类的说法正确的是( )。 A. 内部类只能访问外部的静态成员 B. 内部类只能在外部的方法中被实例化 C. 内部类可以访问外部的私有成员 D. 内部类不能继承其他 答案:C。内部类可以访问外部的私有成员。 2. 下列代码的输出结果是( )。 class Outer { private int num = 10; class Inner { public void print() { System.out.println("num = " + num); } } } public class Test { public static void main(String[] args) { Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.print(); } } A. num = 10 B. num = 0 C. 编译错误 D. 运行时错误 答案:A。内部类可以访问外部的私有成员,因此可以输出num的值。 3. 下列代码的输出结果是( )。 class Outer { private int num = 10; public void method() { class Inner { public void print() { System.out.println("num = " + num); } } Inner inner = new Inner(); inner.print(); } } public class Test { public static void main(String[] args) { Outer outer = new Outer(); outer.method(); } } A. num = 10 B. num = 0 C. 编译错误 D. 运行时错误 答案:A。方法内部定义的局部内部类可以访问外部的成员变量,因此可以输出num的值。 4. 下列说法中关于静态内部类的说法正确的是( )。 A. 静态内部类不能访问外部的静态成员 B. 静态内部类只能在外部的静态方法中被实例化 C. 静态内部类不能访问外部的非静态成员 D. 静态内部类不能继承其他 答案:A。静态内部类不能访问外部的非静态成员,但可以访问外部的静态成员。 5. 下列代码的输出结果是( )。 class Outer { private int num = 10; static class Inner { public void print() { System.out.println("num = " + num); } } } public class Test { public static void main(String[] args) { Outer.Inner inner = new Outer.Inner(); inner.print(); } } A. num = 10 B. num = 0 C. 编译错误 D. 运行时错误 答案:C。静态内部类不能访问外部的非静态成员,因此编译错误。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值